package cn.tsmchina.one.controller.product;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import cn.tsmchina.one.domain.category.Category;
import cn.tsmchina.one.domain.menu.Menu;
import cn.tsmchina.one.domain.product.Product;
import cn.tsmchina.one.service.category.CategoryService;
import cn.tsmchina.one.service.menu.MenuService;
import cn.tsmchina.one.service.product.ProductService;
import cn.tsmchina.one.service.user.CustomerService;
import cn.tsmchina.one.util.C;
import cn.tsmchina.one.util.JsonUtil;
import cn.tsmchina.one.util.LoginUtil;
import cn.tsmchina.one.util.Return;

@Controller
@RequestMapping("/product")
public class ProductController
{
	@Autowired
	private ProductService productService;
	@Autowired
	private MenuService menuService;
	@Autowired
	private CategoryService categoryService;
	@Autowired
	private CustomerService customerService;
	/**
	 * 产品信息
	 * @param request
	 * @return
	 */
	@RequestMapping("/query")
	public String queryOrder(HttpServletRequest request)
	{
		int page = 1;
		try
		{
			String pageStr = request.getParameter("page");
			if(!StringUtils.isEmpty(pageStr))
				page = Integer.parseInt(pageStr);
			long cid = LoginUtil.getCustomerId(request, customerService);
	    	List<Product>	list = productService.getQueryOrder(page, cid);
	    	int total = productService.getTotal(cid);
	    	int pageTotal = total % C.Paging.SIZE == 0 ? total / C.Paging.SIZE : total / C.Paging.SIZE + 1;
	    	request.setAttribute("page", page);
	    	request.setAttribute("total", total);
	    	request.setAttribute("pageTotal", pageTotal);
	    	request.setAttribute("products", list);
	    	request.setAttribute("len", list.size());
	    	
	    	List<String> categories = new ArrayList<String>();
	    	List<String> foodCategories = new ArrayList<String>();
	    	long customerId = LoginUtil.getCustomerId(request, customerService);
	    	for (Product product : list) {
//				String foodCategory = product.getCategory();
				Category fc = categoryService.getById(product.getCategory());
				foodCategories.add(fc.getName());
				String foodCategory = fc.getCid();
				String category = foodCategory.substring(0, 4);
//				Category c = categoryService.getById(category);
				Category c = categoryService.getByCategoryCid(category, customerId);
				categories.add(c.getName());
			}
	    	request.setAttribute("categories", categories);
	    	request.setAttribute("foodCategories", foodCategories);
		} catch (Exception e)
		{
			request.setAttribute("len", 0);
		}
		return "product/queryProduct";
	}
	
	/**
	 * @author  YUE
	 * @date 2013-7-23 上午10:32:38
	 * @param menuName
	 * @param model
	 * @return
	 */
	/*@RequestMapping("/{menuName}")
	public String products(@PathVariable("menuName") String menuName,Model model)
	{
		try
		{
			Map<String,Object> map = productService.getProducts(menuName);
			model.addAttribute("map", map);
		}
		catch (Exception e)
		{
	
		}
		return "product/products";
	}*/
	
	/*@RequestMapping("/item/{productId}")
	public String product(@PathVariable("productId")Long productId,Model model)
	{
		try
		{
			Map<String, Object> product = productService.getProduct(productId);
			System.out.println(JsonUtil.parseJson(product));
			model.addAllAttributes(product);
			model.addAttribute("json",JsonUtil.parseJson(product.get("product")));
		}
		catch (Exception e)
		{
		}
		return "product/product";
	}*/
	
	/*@RequestMapping("/productNumber")
	@ResponseBody
	public Integer getProductNumber(Long id)
	{
		try
		{
			return productService.getProductNumber(id);
		}
		catch (Exception e)
		{
			
		}
		return 0;
	}*/
	/*
	@RequestMapping("/productAll")
	@ResponseBody
	public Map<String, Object> productAll(int page, int pageSize)
	{
		try
		{
			return productService.getProducts(page, pageSize);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return null;
	}
	*/
	/**
	 * 添加产品信息
	 * @return
	 */
	@RequestMapping("/add")
	public String addProduct(Model model, HttpServletRequest request){
		long cid = LoginUtil.getCustomerId(request, customerService);
		List<Menu> list = menuService.getAllMenu();
		model.addAttribute("menus", list);
		List<Category> categories = categoryService.getAllSubRestaurant(cid);
		model.addAttribute("categories", categories);
		
		Map<Integer, String> map = new HashMap<Integer, String>();
		StringBuilder sb = new StringBuilder();
		for (Category category : categories) {
			String pCid = category.getCid();
			List<Category> foods = categoryService.getAllFoodCategory(pCid, cid);
			sb.append("<option value=\"\">---请选择---</option>");
			for (Category category2 : foods) {
				sb.append("<option value=\""+category2.getId()+"\">"+category2.getName()+"</option>");
			}
			map.put(category.getId(), sb.toString());
			sb = new StringBuilder();
		}
		
		model.addAttribute("foods", JsonUtil.parseJson(map));
		return "product/addProduct";
	}
	
	@RequestMapping(value="/add",method= RequestMethod.POST)
	public String addProduct(@ModelAttribute Product product, @RequestParam int foods,HttpServletRequest request)
	{
		try
		{	
			product.setCategory(foods);//只取二级目录id
			productService.addProduct(product);
			request.setAttribute("msgType", C.Msg.OK);
			request.setAttribute("msg", "添加成功!");
			request.setAttribute("return",request.getContextPath()+"/product/query");
		} catch (Exception e)
		{
			request.setAttribute("msgType", C.Msg.ERROR);
			request.setAttribute("msg", "添加失败!");
			request.setAttribute("return",request.getContextPath()+"/product/query");
		}
		return Return.redirect(request);
	}
	
	/**
	 * 产品修改
	 * @param id
	 * @return
	 */
	@RequestMapping("/edit/{id}")
	public String editProduct(@PathVariable("id") long id,HttpServletRequest request)
	{
		Product product = productService.getProduct(id);
		List<Menu> list = menuService.getAllMenu();
		request.setAttribute("p", product);
		request.setAttribute("menus", list);
		request.setAttribute("returnUrl",Return.encode(request.getHeader("referer")));
		
		long cid = LoginUtil.getCustomerId(request, customerService);
		List<Category> categories = categoryService.getAllSubRestaurant(cid);
		request.setAttribute("categories", categories);
		List<Category> foods = categoryService.getAllFoodCategory("0000", cid);//对于本应用，每个店铺的菜品种类肯定是一致的，故为了后台在添加菜品时避免二级目录联动，这里做简化处理
		request.setAttribute("foods", foods);
		
		int categoryId = product.getCategory();
		String categorySid = categoryService.getById(categoryId).getCid();
		request.setAttribute("cid", categorySid.substring(0, 4));
		request.setAttribute("fid", "0000"+categorySid.substring(4));
		return "product/editProduct";
	}
	
	@RequestMapping(value="/edit",method = RequestMethod.POST)
	public String editProduct(@ModelAttribute Product product,@RequestParam String categories, @RequestParam String foods,HttpServletRequest request)
	{
		try
		{
			String categoryCid = categories+foods.substring(4);
			long customerId = LoginUtil.getCustomerId(request, customerService);
			int categoryId = categoryService.getByCategoryCid(categoryCid, customerId).getId();
			product.setCategory(categoryId);//只取二级目录id
			productService.updateProduct(product);
			request.setAttribute("msgType", C.Msg.OK);
			request.setAttribute("msg", "修改成功!");
			request.setAttribute("return", request.getParameter("return"));
		}catch (Exception e)
		{
			request.setAttribute("msgType", C.Msg.ERROR);
			request.setAttribute("msg", "修改失败!");
			request.setAttribute("return", request.getParameter("return"));
		}
		return Return.redirect(request);
	}
	
	/**
	 * 删除产品
	 * @param id
	 * @param request
	 * @return
	 */
	@RequestMapping("/delete/{id}")
	public String deleteProduct(@PathVariable("id") long id, HttpServletRequest request)
	{
		try
		{
			productService.deleteProductById(id);
			request.setAttribute("msgType", C.Msg.OK);
			request.setAttribute("msg", "删除成功!");
			request.setAttribute("return", request.getHeader("referer"));
		} catch (Exception e)
		{
			request.setAttribute("msgType", C.Msg.ERROR);
			request.setAttribute("msg", "删除失败!");
			request.setAttribute("return", request.getHeader("referer"));
		}
		return Return.redirect(request);
	}
	/*@RequestMapping("/createProduct")
	@ResponseBody
	public String createProduct(Product product,HttpServletRequest request)
	{
		try
		{
			String imgSrc = product.getImage();
			String path = request.getSession().getServletContext().getRealPath(imgSrc);
			String smbPut = SmbUtils.smbPut(path);
			System.out.println(smbPut);
			product.setImage(smbPut);
			System.out.println("path:"+path);
			System.out.println(JsonUtil.parseJson(product));
			System.out.println(product.getDescription());
			Long productId = productService.addProduct(product);
			return "success";
		}
		catch (Exception e)
		{
			System.out.println("e-------"+e.getMessage());
			System.out.println(e.getMessage());
			e.printStackTrace();
		}
		return "";
	}*/
	
	/*@RequestMapping("/removeProduct")
	@ResponseBody
	public String removeProduct(Long productId)
	{
		try
		{
			productService.deleteProductById(productId);
			return "Success";
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return "Fail";
	}
	*/
	/*
	@RequestMapping("/updateProduct")
	@ResponseBody
	public String updateProduct(Product product)
	{
		try
		{
			productService.updateProduct(product);
			return "Success";
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return "Fail";
	}
	*/
	
}
